package cz.schovjan.proj.aop;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import cz.schovjan.proj.controllers.Base;
import cz.schovjan.proj.dao.IAdminDao;
import cz.schovjan.proj.dao.impl.HibernateAdminDaoImpl;
import cz.schovjan.proj.entity.UserEntity;
import cz.schovjan.proj.model.User;

/**
 * Advice pro posilani emailu.<br>
 * Pri registraci noveho uzivatele posle email o registraci vsem uzivatelum,
 * s roli ADMIN v systemu.
 * @author schovjan
 *
 */
@Aspect
public class RegistrWatcherAdvice extends Base {

	/** Dao pro vyber adminu */
	private IAdminDao adminDao;

	
	//reaguje na volani fce sendEmailAboutRegister a prijima jeji parametr noveho usera
	@Pointcut("execution(* *.sendEmailAboutRegister (cz.schovjan.proj.model.User)) && args(user)")
	public void regIntoApp(User user) {
	}

	
	@After("regIntoApp(user)")
	public void sendEmail(User user) {
		getLogger().info("doslo k prihlaseni " + user);

		if (adminDao == null) {
			adminDao = new HibernateAdminDaoImpl();
		}
		
			Properties props = new Properties();
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.socketFactory.port", "465");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.port", "465");

			Session session = Session.getDefaultInstance(props,	
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication("jan.schov","9ojdunur");
						}
					});

			List<UserEntity> admins = adminDao.findAll();
			
			if (admins != null) {
				
				String format = "Nick: %s \nJmeno: %s \nPrijmeni: %s \nPodpis: %s \nEmail: %s \nDatum vytvoreni: %s";
				String text = String.format(format, user.getNick(), user.getName(), user.getSurname(), user.getSign(),
											user.getEmail(), user.getDateCreate().toString()); 
						
				for (UserEntity ue : admins) {
					try {
						Message message = new MimeMessage(session);
						message.setRecipients(Message.RecipientType.TO,	InternetAddress.parse(ue.getEmail()));
						message.setSubject("DB kapel: zprava o registraci");
						message.setText("V aplikaci \"DB kapel\" byl zaregistrovan novy uzivatel.\n\nINFORMACE:\n"
								+text+"\n\n\nEmail automaticky odeslan v " + new Date());
						
						Transport.send(message);
					} catch (MessagingException e) {
						getLogger().error("Chyba pri odeslani emailu. " + e);
					}
				}
			}
	}

}
